<template>
  <el-dialog title="给角色分配权限" :visible.sync="dialogVisible" width="48%" @close='clear'>
    <!-- 主体树型区域 -->
    <el-tree :data="rightsList" node-key='id' show-checkbox default-expand-all :props="defaultProps" :default-checked-keys='defKeys' ref="treeRef"></el-tree>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  data: function () {
    return {
      dialogVisible: false,
      // 权限列表
      rightsList: [],
      defaultProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点ID值数组
      defKeys: [],
      // 角色id
      id: 0
    }
  },
  methods: {
    // 权限列表获取并使tree树默认选中
    getRightsList: async function (row) {
      // 1. 获取列表
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.warning('权限列表获取失败')
      }
      this.rightsList = res.data
      this.id = row.id
      // 2.tree数默认选中
      this.getLeafKeys(row, this.defKeys)
    },
    // 遍历所有所有三级叶子节点，并追加进数组
    getLeafKeys: function (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 清空历史痕迹
    clear: function () {
      this.defKeys = []
    },
    // 点击确认，增加角色指定权限
    confirm: async function () {
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const str = key.join(',')
      const res = await this.$http.post(`roles/${this.id}/rights`, { rids: str })
      if (res.meta.status !== 200) {
        return this.$message.warning('角色指定权限添加失败')
      }
      this.$message.success('角色指定权限添加成功！')
      this.$parent.getRoleList()
      this.dialogVisible = false
    }
  }
}
</script>
